package com.taotao.manage.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taotao.common.pojo.EasyUIDataGridResult;
import com.taotao.manage.mapper.ItemDescMapper;
import com.taotao.manage.mapper.ItemMapper;
import com.taotao.manage.pojo.Item;
import com.taotao.manage.pojo.ItemDesc;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;

@Service
public class ItemServiceImpl extends BaseServiceImpl<Item> implements ItemService {

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private ItemDescMapper itemDescMapper;

    /**
     * 保存商品
     */
    @Override
    public Long saveItem(Item item, String desc) {
        saveSelective(item);

        ItemDesc itemDesc=new ItemDesc();
        itemDesc.setItemId(item.getId());
        itemDesc.setItemDesc(desc);
        itemDesc.setCreated(new Date());
        itemDesc.setUpdated(itemDesc.getCreated());
        itemDescMapper.insertSelective(itemDesc);
        return item.getId();
    }

    /**
     * 更新商品
     */
    @Override
    public void updateItem(Item item, String desc) {
        updateSelective(item);

        ItemDesc itemDesc=new ItemDesc();
        itemDesc.setItemId(item.getId());
        itemDesc.setItemDesc(desc);
        itemDesc.setUpdated(new Date());
        itemDescMapper.updateByPrimaryKeySelective(itemDesc);

    }

    @Override
    public EasyUIDataGridResult queryItemList(String title, Integer page, Integer rows) {
        Example example=new Example(Item.class);
        try {
            if(StringUtils.isNotBlank(title)){
                Example.Criteria criteria = example.createCriteria();
                title = URLDecoder.decode(title, "UTF-8");
                criteria.andLike("title","%"+title+"%");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        example.orderBy("updated").desc();
        PageHelper.startPage(page,rows);
        List<Item> list = itemMapper.selectByExample(example);
        PageInfo<Item> pageInfo = new PageInfo<>(list);
        return new EasyUIDataGridResult(pageInfo.getTotal(), pageInfo.getList());
    }
}
